// import Shop from '../model/shop'
import {
	listV2,
	detail,
	queryTestApi,
	batchUploadImageSync,
	searchFolder,
	createFolder,
	publishProduct,
	getCatePropertyV2,
	getProductUpdateRule,
	setOffline,
	del,
	editV2,
	brandListApi
} from "../api/product";
import {
	queryMaterialDetail,
	batchUploadVideoAsync
} from "../api/sysApi/material";
import dlyadminAddProductLog from "../model/DlyAdminAddProductLog";
import EditProductLog from "../model/EditProductLogs";
import fs from "fs";
import { rightsInfo } from "../api/token";
import Shop from "../model/shop";
import ProductAddLog from '../model/productAddLog'

class ProduceController {
	static async listV2(ctx) {
		const bodyJSON = JSON.parse(ctx.request.body);

		const res = await listV2({
			...bodyJSON,
			access_token: ctx.headers.access_token
		});
		ctx.body = res;
	}
	static async detail(ctx) {
		const res = await detail({
			product_id: ctx.query.product_id,
			access_token: ctx.headers.access_token
		});
		ctx.body = res;
	}
	// 提供开放平台测试用API接口
	static async queryTestApi(ctx) {
		// 上传图片
		const res = await queryTestApi({
			folder_id: 0,
			url: "https://wtplug.oss-cn-hangzhou.aliyuncs.com/productImages/JRBtZwqt_m_75560202fd0a2a6791853d31573ae49b_sx_157204_www800-800.jpeg",
			material_name: "www800-800.jpeg",
			access_token: ctx.headers.access_token
		});
		ctx.body = res;
	}

	static async batchUploadImageSync(ctx) {
		// console.log(' ctx.request',  ctx.request.body)
		const files = ctx.request.body;
		if (!files || !files.length) {
			ctx.body = {
				code: 4898,
				msg: "请选择文件"
			};
			return;
		}
		try {
			const getDirectory = await searchFolder({
				order_by: 0,
				page_num: 1,
				page_size: 1,
				name: process.env.FOLDER_NAME,
				parent_folder_id: 0,
				access_token: ctx.headers.access_token
			});
			let folder_id = 0;
			if (getDirectory.code === 10000 && !getDirectory.data.total) {
				const addFlob = await createFolder({
					parent_folder_id: 0,
					name: process.env.FOLDER_NAME,
					type: 0,
					access_token: ctx.headers.access_token
				});
				if (addFlob.code === 10000) {
					folder_id = addFlob.data.folder_id;
				}
			} else {
				folder_id = getDirectory.data.folder_info_list[0].folder_id;
			}
			const filesmifo = JSON.parse(files);
			// console.log('filesmifo', filesmifo)
			const materials = filesmifo.map((res, index) => {
				return {
					request_id: res.request_id,
					folder_id,
					name: res.filename,
					url: res.path,
					material_type: "photo"
				};
			});
			const resD = await batchUploadImageSync({
				materials,
				access_token: ctx.headers.access_token
			});
			// console.log('resD', resD)
			// function getPromiseByUrl(res) {
			// 	return new Promise((resolve, reject) => {
			// 		if (res.code === 10000) {
			// 			setTimeout(async _ => {
			// 				const materialData = Object.keys(res.data.success_map).map((key, index) => {
			// 					return queryMaterialDetail({
			// 						material_id: res.data.success_map[key].MaterialId,
			// 						access_token: ctx.headers.access_token
			// 					})
			// 				})
			// 				const materialDataPro = await Promise.all(materialData)
			// 				resolve(materialDataPro)
			// 			}, 3000)
			// 		}
			// 	})
			// }
			// const materialDataPro = await getPromiseByUrl(resD)
			ctx.body = resD;
		} catch (error) {
			ctx.body = {
				code: 4899,
				msg: "上传失败"
			};
		}
	}

	static async publishProduct(ctx) {
		// console.log('ctx123465', ctx.request.body)
		try {
			console.log("ctx.query.", ctx.query);
			const bodyJSON = JSON.parse(ctx.request.body);
			// console.log('bodyJSON', bodyJSON)
			bodyJSON.access_token = ctx.headers.access_token;
			const res = await publishProduct(bodyJSON);
			console.log("商品创建结果", res);
			/**裂变日志 */
			// new dlyadminAddProductLog({
			// 	shopId: ctx.query.shop_id,
			// 	cretedData: JSON.stringify(res)
			// }).save();
			/**裂变日志 */
			// console.log('add', add)
			// new addProductLogSchema({
			// 	shop_id: ctx.query.
			// }).save()
			ctx.body = res;
		} catch (error) {
			console.log("创建商品错误", error);
			// fs.writeFileSync( __dirname+'/error.log', JSON.stringify(error))
		}
	}
	static async editV2(ctx) {
		// console.log('ctx123465', ctx.request.body)
		try {
			const bodyJSON = JSON.parse(ctx.request.body);

			bodyJSON.access_token = ctx.headers.access_token;

			const res = await editV2(bodyJSON);

			ctx.body = {
				data: res
			};
		} catch (error) {
			// console.log('创建商品错误', error)
			fs.writeFileSync(__dirname + "/error.log", JSON.stringify(error));
		}
	}
	static async getCatePropertyV2(ctx) {
		ctx.verifyParams({
			category_leaf_id: { type: "string", required: true }
		});
		const { category_leaf_id } = ctx.query;
		const res = await getCatePropertyV2({
			category_leaf_id,
			access_token: ctx.headers.access_token
		});
		ctx.body = res;
	}
	static async getProductUpdateRule(ctx) {
		ctx.verifyParams({
			category_id: { type: "string", required: true }
		});
		const res = await getProductUpdateRule({
			category_id: ctx.query.category_id,
			access_token: ctx.headers.access_token
		});
		console.log("结果", res);
		ctx.body = res;
	}
	static async setOffline(ctx) {
		const bodyJSON = JSON.parse(ctx.request.body);

		const res = await setOffline({
			...bodyJSON,
			access_token: ctx.headers.access_token
		});
		ctx.body = res;
	}
	static async del(ctx) {
		const bodyJSON = JSON.parse(ctx.request.body);

		const res = await del({
			...bodyJSON,
			access_token: ctx.headers.access_token
		});
	}
	static async brandList(ctx) {
		ctx.verifyParams({
			category_id: { type: "string", required: true }
		});
		const { category_id, brand_ids = null, query = "" } = ctx.query;
		const res = await brandListApi({
			brand_ids,
			query,
			category_id,
			access_token: ctx.headers.access_token
		});
		ctx.body = res;
	}
	// 异步发布视频
	static async editV2async(ctx) {
		// console.log('ctx.request.body', ctx.request.body.up_modules)
		// console.log('ctx.headers.access_token', ctx.headers.access_token)
		const bodyJSON = ctx.request.body;
		bodyJSON.access_token = ctx.headers.access_token;
		const { up_modules, async_data } = ctx.request.body;
		// console.log('async_data', async_data)

		const { setAddnewLog, TaskId, productId, type } = async_data;

		try {
			// const bodyJSON = JSON.parse(ctx.request.body);

			// bodyJSON.access_token = ctx.headers.access_token;
			const result = await EditProductLog.create({
				TaskId,
				productId,
				statusName: "正在创建",
				status: 0,
				code: -1,
				type,
				setAddnewLog,
				shopName: ctx.request.header.shop_name,
				shopId: ctx.request.header.shop_id
			});
			delete bodyJSON.async_data;
			const res = await editV2(bodyJSON);
			if (res.code === 10000) {
				await result.updateOne({
					status: 1,
					statusName: "编辑成功",
					code: res.code,
					msg: res.msg
				});
			} else {
				await result.updateOne({
					status: 2,
					statusName: "编辑失败",
					code: res.code,
					msg: res.sub_msg
				});
			}

			ctx.body = {
				data: res
			};
		} catch (error) {
			console.log('创建商品错误', error)
			fs.writeFileSync(__dirname + "/error.log", JSON.stringify(error));
		}

		return;
		const result = await EditProductLog.create({
			TaskId,
			productId,
			statusName: "正在创建",
			status: 0,
			code: -1,
			type,
			setAddnewLog,
			shopName: ctx.request.header.shop_name,
			shopId: ctx.request.header.shop_id
		});
		bodyJSON.async_data && delete bodyJSON.async_data;
		// const getshopdata = await Shop.findOne({ shop_id })
		// 扣除useEditNum ++
		await Shop.updateOne(
			{
				shop_id: ctx.request.header.shop_id
			},
			{
				$inc: {
					useEditNum: 1
				}
			}
		);
		// return
		if (!up_modules) {
			// 没有需要上传的素材 直接走发布
			const res = await editV2(bodyJSON);
			if (res.code === 10000) {
				await result.updateOne({
					status: 1,
					statusName: "编辑成功",
					code: res.code,
					msg: res.msg
				});
			} else {
				await result.updateOne({
					status: 2,
					statusName: "编辑失败",
					code: res.code,
					msg: res.sub_msg
				});
			}

			ctx.body = {
				data: res
			};
			return;
		}
		ctx.body = result._id;
		const { video } = up_modules;
		const getDirectory = await searchFolder({
			order_by: 0,
			page_num: 1,
			page_size: 1,
			name: "抖羚羊视频",
			parent_folder_id: 0,
			operate_status: 1,
			access_token: bodyJSON.access_token
		});
		// console.log('getDirectory', getDirectory.data)
		// folder_attr 需要为 0 或者2
		let folder_id = 0;
		if (getDirectory.code === 10000 && !getDirectory.data.total) {
			const addFlob = await createFolder({
				parent_folder_id: 0,
				name: "抖羚羊视频",
				type: 0,
				access_token: bodyJSON.access_token
			});
			if (addFlob.code === 10000) {
				folder_id = addFlob.data.folder_id;
			}
		} else {
			folder_id = getDirectory.data.folder_info_list[0].folder_id;
		}
		// console.log('folder_id', folder_id)
		if (video) {
			// console.log('video', video.url)
			const request_id = Math.random().toString(36).substring(2, 32);
			// console.log('request_id', request_id)
			const batchData = {
				materials: [
					{
						request_id,
						folder_id,
						name: request_id + ".mp4",
						url: video.url,
						material_type: "video"
					}
				],
				access_token: bodyJSON.access_token
			};
			const res = await batchUploadVideoAsync(batchData);
			// console.log('res111', res)
			bodyJSON.up_modules && delete bodyJSON.up_modules;
			if (res.code === 10000) {
				// console.log('res111', JSON.stringify(res.data))

				const getshers = setInterval(async () => {
					const getUpDataShear = await queryMaterialDetail({
						material_id: res.data.success_map[request_id].MaterialId,
						access_token: bodyJSON.access_token
					});
					// console.log('getUpDataShear', getUpDataShear.data.material_info)
					if (getUpDataShear.code === 10000) {
						if (getUpDataShear.data.material_info.audit_status === 3) {
							// console.log('视频审核结果出来', getUpDataShear.data.material_info.video_info.vid)
							let toWebId = bodyJSON.material_video_id;
							bodyJSON.material_video_id =
								getUpDataShear.data.material_info.video_info.vid;

							// console.log('getUpDataShear.data.material_info.audit_status***', getUpDataShear.data.material_info)
							clearInterval(getshers);
							const upNewEdit = setTimeout(async () => {
								// console.log('bodyJSON', bodyJSON)
								// console.log('视频审核结果出来', getUpDataShear.data.material_info.video_info.vid)
								const res = await editV2(bodyJSON);
								// console.log('第一次发布', res)
								setAddnewLog.video.new = bodyJSON.material_video_id;
								if (res.code === 10000) {
									await result.updateOne({
										status: 1,
										statusName: "编辑成功",
										code: res.code,
										msg: res.msg,
										setAddnewLog
									});
								} else if (res.code === 50002) {
									bodyJSON.material_video_id = toWebId;
									const restosetr = await editV2(bodyJSON);
									// console.log('第二次发布', restosetr)
									if (restosetr.code === 10000) {
										await result.updateOne({
											status: 1,
											statusName: "编辑成功",
											code: restosetr.code,
											msg: restosetr.msg
										});
									} else {
										await result.updateOne({
											status: 2,
											statusName: "编辑失败",
											code: restosetr.code,
											msg: restosetr.sub_msg
										});
									}
								} else {
									await result.updateOne({
										status: 2,
										statusName: "编辑失败",
										code: res.code,
										msg: res.sub_msg,
										setAddnewLog
									});
								}
								// console.log('发布成功', res)
								ctx.body = {
									data: res
								};
								clearTimeout(upNewEdit);
							}, 300);

							return;
						} else if (getUpDataShear.data.material_info.audit_status === 4) {
							// console.log('审核拒绝', getUpDataShear.data.material_info)
							// console.log('视频审核中', getUpDataShear.data.material_info.audit_status)
							const asaa = await editV2(bodyJSON);
							// console.log('res222', res)
							if (asaa.code === 10000) {
								await result.updateOne({
									status: 1,
									statusName: "编辑成功",
									code: asaa.code,
									msg: asaa.msg
								});
							} else {
								await result.updateOne({
									status: 2,
									statusName: "编辑失败",
									code: asaa.code,
									msg: asaa.sub_msg
								});
							}
							clearInterval(getshers);
						} else {
							console.log(
								"视频审核中",
								getUpDataShear.data.material_info.audit_status,
								getUpDataShear.data.material_info.video_info
							);
						}
					} else {
						clearInterval(getshers);
					}
				}, 60000);
			}
		}
	}
	static async rightsEditInfo(ctx) {
		const access_token = ctx.headers.access_token;
		const rightsInfoData = await rightsInfo({
			access_token
		});
		// console.log('rightsInfoData', rightsInfoData)
		const shop_id = ctx.request.header.shop_id;
		const getshopdata = await Shop.findOne({ shop_id });
		if (rightsInfoData.code === 10000) {
			ctx.body = {
				rightsType: rightsInfoData.data.rights_type,
				rights: rightsInfoData.data,
				sendEditNum: getshopdata.sendEditNum,
				useEditNum: getshopdata.useEditNum
			};
			return;
		}
		ctx.body = {
			rightsType: 0,
			rights: {},
			sendEditNum: getshopdata.sendEditNum,
			useEditNum: getshopdata.useEditNum
		};
	}

	static async liebianRecord(ctx) {
		try {
			const bodyData = JSON.parse(ctx.request.body);
			const datas = await new ProductAddLog(bodyData).save();
			ctx.body = datas._id;
		} catch (error) {
			ctx.body = {
				code: 500,
				msg: "参数错误"
			}
		}
	}

	static async liebianList(ctx) {
		const query = ctx.query;
		// {shop_id, prduct_id}
		console.log('query', query)

		const getFinders = await ProductAddLog.find({
			shopId: query.shop_id,
			productId: query.product_id
			// $or: [
			// 	{ shopId: query.shop_id, productId: query.product_id },
			// 	{ shopId: query.shop_id, fatherPid: query.product_id }
			// ]
		})
		const fatherPidData = await ProductAddLog.find({ shopId: query.shop_id, fatherPid: query.product_id })
		console.log('getFinders', getFinders, fatherPidData)
		ctx.body = {
			product: getFinders,
			father: fatherPidData
		};
	}
}

export default ProduceController;
